<script lang="ts" setup name="LoginForm">
import useStore from '@/store';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useIntervalFn } from '@vueuse/core'
// 1. 安装包
import { useField, useForm } from 'vee-validate'
import { useCountDown } from '@/utils/hooks';
import { accountValid, codeValid, isAgreeValid, mobileValid, passwordValid } from '@/utils/validate';
import Message from '@/components/XtxMessage';

const { validate, resetForm } = useForm({
  validationSchema: {
    // 账号
    account: accountValid,
    // 密码
    password: passwordValid,
    // 是否同意
    isAgree: isAgreeValid,
    // 手机号
    mobile: mobileValid,
    // 手机号
    code: codeValid
  },
  initialValues:{
    account: 'xiaotuxian001',
    password: '123456',
    isAgree: true,
    mobile: 13012345760,
    code: 123456
    // account: '',
    // password: '',
    // isAgree: false,
    // mobile: '',
    // code: ''
  }
})

// 解构赋值重命名
const { value: account, errorMessage:accountError } = useField<string>('account')
const { value: password, errorMessage:passwordError } = useField<string>('password')
const { value: isAgree, errorMessage:isAgreeError } = useField<boolean>('isAgree')
const { value: mobile, errorMessage:mobileError, validate: mobileValidate } = useField<string>('mobile')
const { value: code, errorMessage:codeError } = useField<string>('code')
// const { value, errorMessage } = useField('password')

const { user, cart  } = useStore()

type LoginType = 'account' | 'mobile'
// 登录的方式
// account: 账号密码
// mobile： 手机号和验证码
const type = ref<LoginType>('account')

const router = useRouter()

const route = useRoute()


// 用户登录
const login = async () => {
  // 手动兜底校验
  // 表单校验
  const res = await validate()
  console.log(res)
  // 尽早返回  == 让函数尽可能早的去return
  // 账号+密码
  if(type.value === 'account'){
    if(res.errors.account || res.errors.password || res.errors.isAgree) { return }
  }else {
    if(res.errors.mobile || res.errors.code || res.errors.isAgree) { return }
  }

  try {
    // 账号+密码
    if(type.value === 'account'){
      await user.login({account: account.value,password:password.value})
    } else {
      await user.mobileLogin(mobile.value, code.value)
    }

    Message.success('登录OK')

    // 登录成功，合并购物车
    await cart.mergeLocalCart()

    // 回跳的地址
    const url = (route.query.redirect as string) || '/'
    router.push(url)
  } catch(err) {
    console.log(err)
    alert(err)
  }
}

const changeType = (newType: LoginType) => {
  // 1. 切换类型
  type.value = newType

  // 2. 重置表单校验
  resetForm()
}

const refMobile = ref<null | HTMLInputElement>(null)
// 用户点击了 发送验证码
// 1. 校验手机号
// 1.1 不通过，让光标定位在手机号，方便用户重写
// 1.2 通过，调用接口发请求

const {counter, start} = useCountDown()
 
const send = async () => {
  if(counter.value > 0) {
    return 
  }
  // 校验手机号
  const res = await mobileValidate()
  if(!res.valid){ // 没有通过校验
    // dom获取焦点
    // ? 是可选链
    refMobile.value?.focus()
    return
  }
  // 调用后端接口，向手机号发验证码
  try {
    await user.sendMobileMsg(mobile.value)
    // 开启倒计时
    start(10)
  } catch (err){
    // alert('error')
  }
}
</script>

<template>
  <div class="account-box">
    <div class="toggle">
      <a @click="changeType('account')" href="javascript:;" v-if="type==='mobile'">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
      <a @click="changeType('mobile')" href="javascript:;" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
      <template v-if="type==='account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input v-model="account" type="text" placeholder="请输入用户名或手机号" />
          </div>
          <!-- 校验失败的提示 -->
          <div class="error" v-if="accountError">
            <i class="iconfont icon-warning" />{{accountError}}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input v-model="password" type="password" placeholder="请输入密码" />
          </div>
          <!-- 校验失败的提示 -->
          <div class="error" v-if="passwordError">
            <i class="iconfont icon-warning" />{{passwordError}}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input type="text" ref="refMobile" v-model="mobile" placeholder="请输入手机号" />
          </div>
          <!-- 校验失败的提示 -->
          <div class="error" v-if="mobileError">
            <i class="iconfont icon-warning" />{{mobileError}}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input type="password" v-model="code" placeholder="请输入验证码" />
            <span class="code" @click="send">{{ counter === 0 ? '发送验证码' : counter+'秒之后再试' }}</span>
          </div>

          <!-- 校验失败的提示 -->
          <div class="error" v-if="codeError">
            <i class="iconfont icon-warning" />{{codeError}}
          </div>

        </div>
      </template>
      <div class="form-item">
        <div class="agree">
         
          <!-- <span>我已同意</span> -->
          <!-- <input type="checkbox" v-model="xxxx"/> -->
          <!-- v-model="isAgree" 
            :modelValue
            @update:modelValue
          -->
          <XtxCheckbox v-model="isAgree">我已同意</XtxCheckbox>

          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>

        <!-- 校验失败的提示 -->
          <div class="error" v-if="isAgreeError">
            <i class="iconfont icon-warning" />{{isAgreeError}}
          </div>

      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
    </div>
    <div class="action">
      <a href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&amp;response_type=token&amp;scope=all&amp;redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"><img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="QQ登录" border="0"></a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
        }
        .code {
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      cursor: pointer;
    }
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>